import smeRouter from "sme-router"
import moment from "moment"

import {
  getAdmins,
  getOneAdmin,
  reqAddAdmin,
  reqDelAdmin,
  reqUpdateAdmin,
} from "./api/admin"
import index from "./views/index.ejs"
import login from "./views/login.ejs"
import adminList from "./views/adminList.ejs"
import advList from "./views/advList.ejs"
import { reqLogin, reqVerifyToken, reqLogout } from "./api/login"
import { reqAddAdv, getAdvs, delAdv, getOneAdv, updateAdv } from "./api/adv"

const router = new smeRouter("root", "html5")

window.router = router
window.moment = moment

async function isEnableToken(res) {
  await new Promise(async (resolve, reject) => {
    const verifyResult = await reqVerifyToken()
    if (verifyResult.success) {
      resolve()
    } else {
      reject()
      toastr.error(verifyResult.msg)
      res.redirect("/login")
    }
  })
}

router.route("/login", (req, res, next) => {
  res.render(login())
  $("#loginBtn").on("click", async function (e) {
    e.preventDefault()
    const username = $("#loginForm input[type=text]").val().trim()
    const password = $("#loginForm input[type=password]").val().trim()
    if (!(/^\w{2,8}$/.test(username) && /^\w{6,8}$/.test(password)))
      return toastr.error("请输入正确的用户名或密码")
    const result = await reqLogin(username, password)
    if (result.success) {
      localStorage.setItem("authorization", result.token)
      res.redirect("/index", result.admin)
    } else {
      return toastr.error("请输入正确的用户名和密码")
    }
  })
})

router.route("/index", async (req, res, next) => {
  await isEnableToken(res)
  next(
    index({
      subRoute: res.subRoute(),
      url: req.url,
      admin: req.body,
    })
  )

  //退出登录操作
  $("#logoutBtn").on("click", async function () {
    const id = $("#logoutBtn")[0].dataset.id
    await reqLogout(id)
    localStorage.clear()
    res.redirect("/login")
  })
})

// 管理员列表页
router.route("/index/adminList", async (req, res, next) => {
  await isEnableToken(res)
  const result = await getAdmins()
  if (result.success) {
    res.render(adminList({ adminList: result.data }))
  } else {
    toastr.error(result.msg)
  }

  //验证添加的管理员名字是否重复
  $("#exampleInputEmail1").on("blur", async function () {
    const username = $("#exampleInputEmail1").val()
    if (username) {
      const result = await getOneAdmin(username)
      if (!result.success) {
        toastr.error(result.msg)
      }
    }
  })

  //点击添加管理员弹出框渲染
  $("#addAdminBtn").on("click", function () {
    $("#exampleInputEmail1").removeAttr("readonly") 
    $("#addForm")[0].reset()
    $(".modal-title")[0].innerText = "添加管理员"
    $("#saveAdmin")[0].innerText = "添加"
    $("#saveAdmin")[0].dataset.id = ""
  })

  $("#saveAdmin").on("click", async function () {
    if ($("#saveAdmin")[0].innerText === "添加") {
      const formData = new FormData($("#addForm")[0])
      const username = formData.get("username")
      const password = formData.get("password")
      const repassword = formData.get("repassword")
      if (!(username && password) || password !== repassword)
        return toastr.error("请输入正确的管理员账号信息")
      const result = await reqAddAdmin(formData)
      if (result.success) {
        toastr.success("管理员添加成功")
        res.redirect("/index/adminList")
      }
    } else if ($("#saveAdmin")[0].innerText === "保存") {
      const password = $("#exampleInputPassword1").val()
      const repassword = $("#examplereInputPassword").val()
      if (password && repassword && password === repassword) {
        const id = this.dataset.id
        const result = await reqUpdateAdmin(id, password)
        if (result.success) {
          toastr.success("密码修改成功")
          res.redirect("/index/adminList")
        }
      } else {
        toastr.error("请输入正确的密码")
      }
    }
  })

  //修改密码点击后的渲染
  $("#tbody .btn-primary").on("click", async function (e) {
    $("#addForm")[0].reset()
    $(".modal-title")[0].innerText = "修改管理员密码"
    $("#saveAdmin")[0].innerText = "保存"
    const id = this.dataset.id
    const username = this.dataset.username
    $("#saveAdmin")[0].dataset.id = id
    $("#exampleInputEmail1").val(username)
    $("#exampleInputEmail1").attr({ readonly: "readonly" })
  })

  //删除一个管理员
  $(".btn-danger").on("click", async function (e) {
    const id = this.dataset.id
    const result = await reqDelAdmin(id)
    if (result.success) {
      res.redirect("/index/adminList")
    }
  })
})

//广告列表页
router.route("/index/advList", async (req, res, next) => {
  await isEnableToken(res)
  const result = await getAdvs()
  res.render(advList({ advList: result.data }))

  // 点击添加按钮清空表单数据
  $("#addAdvBtn").on("click", function () {
    $(".modal-header .modal-title").text("添加广告")
    $("#saveAdv").text("保存")
    $("#form")[0].reset()
    $("#preshow")[0].style.display = "none"
  })

  // 设置添加图片文件时候的预览效果
  $("#file").on("change", (e) => {
    if (!e.target.files.length) return ($("#preshow")[0].style.display = "none")
    const file = e.target.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = function (e) {
      const imgData = e.target.result
      $("#preshow")[0].src = imgData
      $("#preshow")[0].style.display = "block"
    }
  })

  //提交、修改添加的广告信息表单
  $("#saveAdv").on("click", async function (e) {
    const formData = new FormData($("#form")[0])
    const title = formData.get("advTitle")
    const category = formData.get("advCategory")
    const link = formData.get("advLink")
    const file = formData.get("file")
    if (this.innerText === "保存") {
      if (!(title && category && link && file.size))
        return toastr.error("请输入正确的表单内容")
      const result = await reqAddAdv(formData)
      if (result.success) {
        toastr.success(result.msg)
        res.redirect("/index/advList")
      } else {
        toastr.error(result.msg)
      }
    } else {
      if (!(title && link && category))
        return toastr.error("请输入正确的表单内容")
      const id = $("#saveAdv")[0].dataset.id
      formData.append("id", id)
      const result = await updateAdv(formData)
      if (result.success) {
        toastr.success(result.msg)
        res.redirect("/index/advList")
      } else {
        toastr.error(result.msg)
      }
    }
  })

  //删除一条广告数据
  $("#tbody .btn-danger").on("click", async function () {
    const id = this.dataset.id
    const result = await delAdv(id)
    if (result.success) {
      res.redirect("/index/advList")
    }
  })

  //广告数据点击删除弹出框动态渲染
  $("#tbody .btn-primary").on("click", async function () {
    $(".modal-header .modal-title").text("修改广告")
    $("#saveAdv").text("修改")
    const id = this.dataset.id
    $("#saveAdv").attr("data-id", id)
    const { adv } = await getOneAdv(id)
    $("input[name=advTitle]").val(adv.advTitle)
    $("input[name=advCategory]").val(adv.advCategory)
    $("input[name=advLink]").val(adv.advLink)
    $("#preshow")[0].src = adv.advAvatar
    $("#preshow")[0].style.display = "block"
  })
})
router.route("*", (req, res, next) => {
  res.redirect("/login")
})
